#!/usr/bin/env python
#-*- coding:utf8 -*-
import os
import sys
import re
import hashlib
import web
import urllib
import urllib2
import json
import dns.resolver as dns
class Helper(object):

    @classmethod
    def print_object(cls,obj):
        print ', '.join(['%s:%s' % item for item in obj.__dict__.items()])

    @classmethod
    def validation(cls,rexp,val):
        rexp = re.compile(rexp)
        return bool(rexp.match(val))

    @classmethod
    def post(cls):
        return Helper.htmlquote(dict(web.input()))

    @classmethod
    def htmlquote(cls,post):
        if isinstance(post,dict) == False:
            return web.net.htmlunquote(post)
        else:
            for key,val in post.items():
                post[key] = Helper.htmlquote(val)
        return post

    @classmethod
    def hash(cls,vals):
        return hashlib.md5(str(vals)).hexdigest()

    @classmethod
    def dict_filter(cls,dicts):
        return dict(filter(lambda x: x[1] != None, dicts.items()))

    @classmethod
    def is_ipv4(ipv4,val):
        if  Helper.validation(r"^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$",val):
            return True,'IP格式正确.'
        return False,'IP格式不正确.'

    @classmethod
    def get_cname(cls,val):
        try:
            cnames = dns.query(val,'CNAME')
        except:
            return False
        for cname in cnames:
            cname = cname
        if str(cname) == 'dns1.sicool.cc.':
            return True
        return False

    @classmethod
    def sizeof_fmt(cls,val):
        for x in ['bytes','KB','MB','GB']:
            if num < 1024.0 and num > -1024.0:
                return "%3.1f%s" % (num, x)
            num /= 1024.0
        return "%3.1f%s" % (num, 'TB')

    @classmethod
    def get_node_api(cls,uri):
        try:
            return json.loads(urllib2.urlopen(uri,timeout = 6).read())
        except:
            return None
